<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="全自注意力网络Transformer详解, J Sir">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>全自注意力网络Transformer详解 | J Sir</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 6.0.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
</head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">J Sir</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">J Sir</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/jy741" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/jy741" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/23.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">全自注意力网络Transformer详解</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/">
                                <span class="chip bg-color">机器学习</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2022-11-02
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    3.3k
                </div>
                

                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="EverydayOneCat"><a href="#EverydayOneCat" class="headerlink" title="EverydayOneCat"></a>EverydayOneCat</h1><p>🐈👈🐱 🛏️➡️🛌</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/573defbb1f3c6e17c38fa65ed459487fecbe3973.jpg@1036w.webp" alt="img" style="zoom:50%;"></p>
<h1 id="Transformer"><a href="#Transformer" class="headerlink" title="Transformer"></a>Transformer</h1><p>2017 年，Google 在论文 <a target="_blank" rel="noopener" href="https://arxiv.org/abs/1706.03762">Attention is All you need</a> 中提出了 <a target="_blank" rel="noopener" href="https://so.csdn.net/so/search?q=Transformer&amp;spm=1001.2101.3001.7020">Transformer</a> 模型，其使用 <strong>Self-Attention</strong> 结构取代了在 NLP 任务中常用的 RNN 网络结构。相比 RNN 网络结构，其最大的优点是可以并行计算。</p>
<h2 id="Sequence-to-sequence-Seq2seq"><a href="#Sequence-to-sequence-Seq2seq" class="headerlink" title="Sequence-to-sequence (Seq2seq)"></a>Sequence-to-sequence (Seq2seq)</h2><p>Seq2Seq的含义就是input是一个向量序列，output也是一个向量序列，并且output的长度由机器自己决定。</p>
<p>有很多场景都会用到Seq2Seq，如Text-to-Speech (TTS) Synthesis、Chatbot、Syntactic Parsing、Multi-label Classification等等</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221102212629827.png" alt="image-20221102212629827" style="zoom:80%;"></p>
<p>Seq2Seq主要结构分为两部分：Encoder（编码器）和Decoder（解码器）</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221102213507041.png" alt="image-20221102213507041"></p>
<p>而目前我们在Seq2Seq场景使用的最常用的模型就是<a target="_blank" rel="noopener" href="https://arxiv.org/abs/1706.03762">Transformer</a>，整体结构如下图：</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221102213629899.png" alt="image-20221102213629899" style="zoom:80%;"></p>
<h2 id="Encoder"><a href="#Encoder" class="headerlink" title="Encoder"></a>Encoder</h2><p>编码器Encoder的任务其实就是input一排向量集，output同等数量的向量集。这里就用到了我们上篇提到的self-attention，当然CNN和RNN也都能实现，但是效果不太好，主要原因可以看<a href="https://jy741.gitee.io/2022/10/31/zi-zhu-yi-li-ji-zhi-self-attention/#toc-heading-11">《自注意力机制Self-Attention》</a></p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221102213940611.png" alt="image-20221102213940611" style="zoom:80%;"></p>
<p>Transformer中的Encode具体结构如下：</p>
<ol>
<li>在inputs的地方加上了positional encoding，如果你只用self-attention,没有未知的资讯，所以需要加上positional的information。</li>
<li>Multi-Head Attention：这里就是self-attention的block,然后专门强调说它是Multi-Head的self-attention。</li>
<li>Add&amp;Norm：就是residual残差结构加上layer normalization</li>
<li>Feed Forward: 是FC的feed forward network</li>
<li>N×：Block会重复N次</li>
</ol>
<p>Encoder里面会分成很多的block，每个block都是输入一排向量输出一排向量。</p>
<p>但是每个block并不是neural network的一层（layer），是因为一个block里面是好几个layer在做事情。</p>
<p>Transformer里面的block结构：</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221102220509393.png" alt="image-20221102220509393" style="zoom:80%;"></p>
<p>每个Block里的工作：输入一排向量—&gt;经过self-attention处理—&gt;输出一排向量—&gt;在将输出的每个向量丢到fully connected的feed forward network里面在outout另外一排vector。</p>
<p>我们可以改进Block结构：加入残差residual结构，我们不只是输出一个vector，还要把输出的vector在加上它的input的到新的output。</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221102220614866.png" alt="image-20221102220614866" style="zoom:80%;"></p>
<p>得到residual 的结果以后在经过norm，这里的norm不是batch normalization，用的是layer normalization。它做的事情比bacth normalization更简单一点，简而言之norm就是输入一个向量输出一个向量，不用考虑batch的资讯，过程就是对同一个feature同一个example里面不同的dimension去计算它的mean跟standard deviation，然后在经过标准化就是layer normalization的输出。这个输出后面是FC的输入，而FC里面也有residual的架构，我们会把FC network的input跟它的output加起来做一下residual得到新的输出，再把这个输出做一次layer normalization得到的才是真正的输出，这个输出才是transform encoder里面一个block的输出。</p>
<blockquote>
<p>目前也有更多的研究觉得初始Transformer结构存在可优化的地方：</p>
<p>左边<a target="_blank" rel="noopener" href="https://arxiv.org/abs/2002.04745">论文</a>将layer normalization的顺序调整会达到更优的效果</p>
<p>右边<a target="_blank" rel="noopener" href="https://arxiv.org/abs/2003.07845">论文</a>讲解为什么batch normalization不如layer normalization</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221102220903993.png" alt="image-20221102220903993"></p>
</blockquote>
<h2 id="Decoder"><a href="#Decoder" class="headerlink" title="Decoder"></a>Decoder</h2><p>decoder其实有两种：Autoregressive (AT) 和Non-autoregressive(NAT)</p>
<h3 id="Autoregressive-AT"><a href="#Autoregressive-AT" class="headerlink" title="Autoregressive (AT)"></a>Autoregressive (AT)</h3><p>我们举例语音辨识过程来了解它的运作过程。</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221102221524755.png" alt="image-20221102221524755" style="zoom:80%;"></p>
<p>首先，输入一个声音讯号，经过encoder输出一组vector, 然后将这个输出当作decoder的输入，最后产生语音辨识的结果。</p>
<p>如果要处理NLP的问题，每一个token都可以把他用一个ONe-Hot的Vector（其中一维是1，其他都是0）来表示，所以begin也是用ONe-Hot Vector来表示。然后decoder吐出一个向量，这个vector的长度非常长，跟vocabulary的size是一样的。</p>
<blockquote>
<p>Vocabulary：首先知道decoder输出的单位是什么? 假设是中文的语音辨识，那这里vocabulary的size可能就是中文的方块字的数目。要是英文的话，用字母数量会很少，用单词数量又会太多，所以可以用Subword当作英文的单位，即单词的字首字根的组合，数量适中。</p>
</blockquote>
<p>然后输出的向量中的每一个中文的字通过softmax都会对应一个数值，数值最高的那一个中文字就是最终的输出。</p>
<p>在上图的例子中，我们Begin的input会对应“机”的输出。然后把”机”当作是decoder新的input, 原来只有bengin一个输入，现在在加上“机”，“机”也可表示成一个ONe-Hot的Vector作为decoder的输入，所以现在有两个输入，然后就得到一个输出向量，在根据这个向量里面给出的每一个中文字的分数得到分值最高的输出，后面依次循环。Encoder的输出也会参与到这个过程中来。</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221102222003897.png" alt="image-20221102222003897"></p>
<blockquote>
<p>这里就会有一个问题：当decoder在产生一个句子的时候，它其实有可能在中途产生错误的输出，因为它是将自己的输出作为产生下一个字符的输入，而那个输出有可能是错误的。让decoder看到自己产生出来的错误的输入，再被decoder自己吃进去会不会造成Error Propagation（一步错，步步错）的问题呢？</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221102222116233.png" alt="image-20221102222116233" style="zoom:80%;"></p>
</blockquote>
<p>下图是Decoder的内部结构：</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221102222331152.png" alt="image-20221102222331152" style="zoom:80%;"></p>
<p>我们发现如果decoder中间遮住一部分，就会发现和encoder两者基本相同，如下图：</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221102222422811.png" alt="image-20221102222422811" style="zoom:80%;"></p>
<p>不同点：</p>
<p>（1）Decoder最后会做一个softmax，使得它的输出变成一个几率</p>
<p>（2）加了一个Masked</p>
<p>为什么需要加入Masked，具体原因如下：</p>
<p>我们知道原本的self-attention，输入一排vector，输出一排vector，这个vector的每一个输出都要看过完整的input之后才做决定，其实输出b1的时候其实是根据a1到a4所有的资讯去输出b1。</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/v2-83d76002dee7a0aff310f24f488835f6_720w.webp" alt="img"></p>
<p>如上图，当self-attention转成Masked Attention的时候，他的不同点是，现在我们不能再看右边的部分，也就是我们产生b1的时候只能考虑a1的资讯，不能去看a2、a3、a4，产生b2的时候只能考虑a1、a2的资讯，不能考虑a3、a4的资讯，后面类似，最后产生b4时可以考虑所有的资讯。这就是Masked的self-attention。</p>
<p>更具体点，当产生b2时，只拿第二个位置a2的Query去跟第一个位置的Key和第二个位置的Key去计算Attention，第三个位置和第四个位置不用去管它。</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/v2-b0af80dba449b2658e3d634783c30682_720w.webp" alt="v2-b0af80dba449b2658e3d634783c30682_720w"></p>
<blockquote>
<p>Why masked？</p>
<p>一开始decoder的运作方式它是一个一个输出的，是先有a1，再有a2，然后是a3、a4,所以当计算b2时是没有a3和a4的，所以没办法将后面的考虑进来。</p>
<p>这跟原来的Self-Attention不一样，原来的Self-Attention中a1到a4是一次整个输入到Model里面的。</p>
</blockquote>
<p>关键问题：Decoder自己决定输出的长度，但是到底输出的sequence的长度应该是多少呢？也就是机器如何决定该何时停下来。这里没办法决定，输出多少输出多少是非常复杂的，我们其实是期望机器可以自己学到。</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221102223001465.png" alt="image-20221102223001465" style="zoom:80%;"></p>
<p>如上图，准备一个特别的符号“断”，用end来表示这个特别的符号，其实begin和end可以用同一个符号，因为begin只在开始时会出现一次。</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221102223040666.png" alt="image-20221102223040666" style="zoom:80%;"></p>
<p>机器要自己知道在将自己的输出“习”再次当作输入时，要能够判断出现在应该输出end。</p>
<h3 id="Non-autoregressive-NAT"><a href="#Non-autoregressive-NAT" class="headerlink" title="Non-autoregressive (NAT)"></a>Non-autoregressive (NAT)</h3><p>AT VS NAT：</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221103134520291.png" alt="image-20221103134520291"></p>
<p>如图可见，AT是输入一个begin，输出一个字符，输入一个输出一个。而NAT是一次性输入全部的begin，然后输出全部的字符。</p>
<p>这里会出现相同的问题：输出的长度怎么来确定呢？</p>
<p>有两个办法：</p>
<p>（1）另外取一个classfier，这个classifier输入encoder的input，输出一个数字，这个数字代表应该要输出的长度。</p>
<p>（2）输入一堆begin的token，也就是大于输出上限值数量的输入，所以输出一堆的字符，忽略end后面的只取前面的字符。</p>
<p>NAT的好处：</p>
<p>（1）平行化：AT输出时是一个一个产生的，所以要输出100个字的句子，就要做一百次的decoder。但是NAT的decoder不管句子的长度如何，都是一个步骤就产生出完整的句子。速度上NAT的decoder会跑的比AT快。</p>
<p>（2）可以控制输出的长度。例如语音合成时，如果想要系统讲话快一点，就可以把classfier的output除以二，讲话的速度就会变成二倍速。同理，放慢速度就将输出的长度乘以二。</p>
<p>Nat通常比At的表现差。</p>
<h2 id="Encoder-Decoder"><a href="#Encoder-Decoder" class="headerlink" title="Encoder-Decoder"></a>Encoder-Decoder</h2><p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221103135300902.png" alt="image-20221103135300902"></p>
<p>圈起来的那部分叫做Cross attention，它是连接Encoder跟Decoder之间的桥梁，从图中可以看出，这个模块的输入部分，有两个箭头来自encoder，一个来自decoder。</p>
<p>模块Cross attention实际运作过程：</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221103135423935.png" alt="image-20221103135423935"></p>
<p>如上图，decoder就是产生一个q，去encoder那边抽取资讯出来当作接下来decoder里面的Fully-Connected 的Network的Input。具体来说就是，q和k1、k2、k3去计算分数，然后在和v1、v2、v3做Weighted Sum做加权，加起来得到v’,然后交给Fully-Connected处理。</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221103140508803.png" alt="image-20221103140508803"></p>
<p>如上图，输入一段声音讯号，第一个而应该要输出的中文字是机，所以当我们把begin丢给decoder的时候，它的第一个输出要跟机越接近越好，即“机”这个字会被表示成一个One-Hot的Vector，在这个vector里面只有机对应的那个维度为1，而decoder的输出是一个Distribution是一个几率的分布，我们希望这个几率的分布跟One-Hot的Vector越接近越好。所以去计算Ground truth和distribution之间的Cross Entropy，希望这个Cross Entropy的值越小越好。</p>
<p>总体来说这件事情跟分类很像，我们可以想象，每一次Decoder在产生一个中文字的时候，其实就是做了一次分类问题，中文字假设有四千个，那就是做有四千个类别的分类的问题。</p>
<p>Teacher forcing：训练时给正确的答案作为Decoder的输入。</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221103140653564.png" alt="image-20221103140653564"></p>
<p>首先，我们已经知道输出应该是机器学习这四个字，然后告诉decoder它的正确输出应该是机器学习这四个中文字的One-Hot Vector，我们希望输出跟这四个字的One-Hot Vector越接近越好，在训练的时候每一个输出都会有一个Cross Entropy，每一个输出跟One-Hot Vector 跟他对应的正确答案都有一个Cross Entropy，最后我们希望所有的Cross Entropy的总和最小。</p>
<p>现在还有end的问题，机器要输出的不只是四个字，还有一个end，所以要让机器知道输出四个字以后，还要记着输出“断”。所以应该告诉decoder第五个位置的输出应该跟断的One-Hot Vector它的Cross Entropy越小越好。这个就是Decoder的训练。</p>
<p>这个训练会产生一个问题：训练的时候decoder会得到正确的答案作为输入，但是testing时decoder得到的是自己上一个的输出，这中间显然会有一个Mismatch。</p>
<h2 id="Tips-for-Seq2Seq"><a href="#Tips-for-Seq2Seq" class="headerlink" title="Tips for Seq2Seq"></a>Tips for Seq2Seq</h2><p>（1）Copy Mechanism:对一些任务而言，decoder没有必要产生输出，它要做的是从输入的东西中复制一些出来，像这种复制行为的例子有聊天机器人。</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221103141040085.png" alt="image-20221103141040085"></p>
<p>（2）Guided Attention：它要做的事情就是要求机器去领导这个Attention的过程，要求机器去做attention的时候是有固定的方式的。</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221103141308774.png" alt="image-20221103141308774"></p>
<p>对于语音合成或者语音辨识来说，我们想象中的Attention应该是由左往右的，上图中红色曲线代表Attention的分数，若是语音合成的话，应该先看最左边输入的词去产生声音，再根据中间的词汇去产生声音，最后看右边的词汇产生声音。但是当你做语音合成时发现机器的读取顺序是颠三倒四的，显然是错的，无法合成出好的结果。而Guided Attention在这里要做的事情就是强迫Attention有一个固定的样貌，将这个必须从左到右的限制放到training里面，要求机器学到Attention就应该从左到右。</p>
<p>（3）Beam Search</p>
<p>举个例子来解释：</p>
<p><img src="https://pluto-1300780100.cos.ap-nanjing.myqcloud.com/img/image-20221103141337517.png" alt="image-20221103141337517"></p>
<p>假设现在的decoder只能产生两个字，只能产生两个可能的输出一个是A，另一个为B。那对decoder而言，他做的事情就是在每一次第一个Time Step，在A、B里面决定一个，假如决定A以后将A当作输入在决定A、B要选哪一个，依次向后进行。在这个过程中，每一次Decoder都是选分数最高的那一个，但是有时候刚开始选分数高的，后面还是有可能差下来，还有时候一开始选择分数低点的，后面反而会更好。所以就可以通过Beam Search这个技术来找一个approximate不是完全精准的估测的solution。</p>
<p>现在对于Beam Search的评价有好有坏，当然了，要看具体的任务需求，若一个任务它的答案非常明确，例如语音识别，有唯一明确的答案，通常Beam Search就会比较有帮助。如果需要机器发挥一点创造力的时候，Beam Search的帮助就会很小。</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">J Sir</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://jy741.gitee.io/2022/11/02/quan-zi-zhu-yi-li-wang-luo-transformer/">https://jy741.gitee.io/2022/11/02/quan-zi-zhu-yi-li-wang-luo-transformer/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">J Sir</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/">
                                    <span class="chip bg-color">机器学习</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2022/12/06/sheng-cheng-shi-dui-kang-wang-luo-gan/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/13.jpg" class="responsive-img" alt="生成式对抗网络GAN">
                        
                        <span class="card-title">生成式对抗网络GAN</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            EverydayOneCat很多很多很多💃💃🕺🕺 

                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2022-12-06
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            J Sir
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/">
                        <span class="chip bg-color">机器学习</span>
                    </a>
                    
                    <a href="/tags/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/">
                        <span class="chip bg-color">深度学习</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2022/10/31/zi-zhu-yi-li-ji-zhi-self-attention/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/5.jpg" class="responsive-img" alt="自注意力机制Self-Attention">
                        
                        <span class="card-title">自注意力机制Self-Attention</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            EverydayOneCat稍稍2 🌈

                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2022-10-31
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            J Sir
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/">
                        <span class="chip bg-color">机器学习</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4, h5'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4, h5').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>


<script src="https://cdn.bootcss.com/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
    MathJax.Hub.Config({
        tex2jax: {inlineMath: [['$', '$'], ['\(', '\)']]}
    });
</script>



    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2020-2023</span>
            
            <span id="year">2020</span>
            <a href="/about" target="_blank">J Sir</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">300.9k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">


    <a href="mailto:2065373132@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2065373132" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2065373132" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

	
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"live2d-widget-model-hibiki"},"display":{"position":"right","width":145,"height":315},"mobile":{"show":true,"scale":0.5},"react":{"opacityDefault":0.7,"opacityOnHover":0.8},"log":false});</script></body>

</html>
